import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
  MapPin,
  Hospital,
  Flame,
  Shield,
  MessageSquare,
  Plus,
  Trash2,
  Sparkles,
  BookOpen,
  Check,
  FolderDown,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Checkbox } from "@/components/ui/checkbox";
import { ScrollArea } from "@/components/ui/scroll-area";
import { EmergencyMeasureTemplateAPI } from "@/api/EmergencyMeasureTemplate";
import { SafetyRiskPointAPI } from "@/api/SafetyRiskPoint";
import { useToast } from "@/components/ui/use-toast";
import { InvokeLLM } from "@/api/integrations";
import { Label } from "@/components/ui/label";

const EmergencyMeasureImportModal = ({ open, onOpenChange, onImport }) => {
  const [templates, setTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedTemplateIds, setSelectedTemplateIds] = useState(new Set());

  useEffect(() => {
    if (open) {
      setIsLoading(true);
      EmergencyMeasureTemplateAPI.getList()
        .then((res) => {
          const processedData = res.data.map((t) => ({
            ...t,
            id: t.id || `temp-${Math.random().toString(36).substr(2, 9)}`,
          }));
          setTemplates(processedData);
        })
        .catch((err) => console.error("Failed to load measure templates", err))
        .finally(() => setIsLoading(false));
    }
  }, [open]);

  const handleToggleSelection = (id) => {
    setSelectedTemplateIds((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const handleConfirmImport = () => {
    const selectedTemplates = templates.filter((t) =>
      selectedTemplateIds.has(t.id)
    );
    onImport(selectedTemplates);
    onOpenChange(false);
    setSelectedTemplateIds(new Set());
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>从知识库导入应急措施</DialogTitle>
          <DialogDescription>
            选择一个或多个标准应急措施模板添加到方案中。
          </DialogDescription>
        </DialogHeader>
        <div className="py-4">
          {isLoading ? (
            <p>加载中...</p>
          ) : (
            <ScrollArea className="h-[400px] border rounded-md p-4">
              <div className="space-y-4">
                {templates.length === 0 ? (
                  <p className="text-center text-gray-500">暂无可用模板。</p>
                ) : (
                  templates.map((template) => (
                    <div
                      key={template.id}
                      className="flex items-start gap-4 p-2 rounded-lg hover:bg-gray-50"
                    >
                      <Checkbox
                        id={`template-${template.id}`}
                        checked={selectedTemplateIds.has(template.id)}
                        onCheckedChange={() =>
                          handleToggleSelection(template.id)
                        }
                      />
                      <label
                        htmlFor={`template-${template.id}`}
                        className="flex-1 cursor-pointer"
                      >
                        <p className="font-semibold text-gray-800">
                          {template.incident_type}
                        </p>
                        <p className="text-sm text-gray-600">
                          {template.description}
                        </p>
                      </label>
                    </div>
                  ))
                )}
              </div>
            </ScrollArea>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button
            onClick={handleConfirmImport}
            disabled={selectedTemplateIds.size === 0}
          >
            <Check className="w-4 h-4 mr-2" />
            导入 ({selectedTemplateIds.size})
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

const EmergencyContactEditor = ({ contacts, onUpdate, disabled }) => {
  const updateContactField = (type, field, value) => {
    const updated = {
      ...contacts,
      [type]: {
        ...contacts[type],
        [field]: value,
      },
    };
    onUpdate({ emergencyContacts: updated });
  };

  const safeContacts = {
    hospital: contacts?.hospital || {
      name: "",
      address: "",
      phone: "",
      directions: "",
    },
    fireDepartment: contacts?.fireDepartment || {
      name: "",
      address: "",
      phone: "",
      directions: "",
    },
    policeStation: contacts?.policeStation || {
      name: "",
      address: "",
      phone: "",
      directions: "",
    },
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <MapPin className="w-5 h-5 text-blue-600" />
          施工地点附近外援机构
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-6">
          <div className="space-y-3">
            <h4 className="font-medium text-gray-800 flex items-center gap-2">
              <Hospital className="w-4 h-4 text-green-600" />
              最近医院
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 pl-6">
              <div>
                <label className="text-sm text-gray-600">医院名称</label>
                <Input
                  value={safeContacts.hospital.name}
                  onChange={(e) =>
                    updateContactField("hospital", "name", e.target.value)
                  }
                  placeholder="输入医院名称"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div>
                <label className="text-sm text-gray-600">联系电话</label>
                <Input
                  value={safeContacts.hospital.phone}
                  onChange={(e) =>
                    updateContactField("hospital", "phone", e.target.value)
                  }
                  placeholder="输入联系电话"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">医院地址</label>
                <Input
                  value={safeContacts.hospital.address}
                  onChange={(e) =>
                    updateContactField("hospital", "address", e.target.value)
                  }
                  placeholder="输入医院地址"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">导航路线</label>
                <Textarea
                  value={safeContacts.hospital.directions}
                  onChange={(e) =>
                    updateContactField("hospital", "directions", e.target.value)
                  }
                  placeholder="输入从施工现场到医院的导航路线"
                  rows={2}
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
            </div>
          </div>
          <div className="space-y-3">
            <h4 className="font-medium text-gray-800 flex items-center gap-2">
              <Flame className="w-4 h-4 text-red-600" />
              最近消防中心
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 pl-6">
              <div>
                <label className="text-sm text-gray-600">消防中心名称</label>
                <Input
                  value={safeContacts.fireDepartment.name}
                  onChange={(e) =>
                    updateContactField("fireDepartment", "name", e.target.value)
                  }
                  placeholder="输入消防中心名称"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div>
                <label className="text-sm text-gray-600">联系电话</label>
                <Input
                  value={safeContacts.fireDepartment.phone}
                  onChange={(e) =>
                    updateContactField(
                      "fireDepartment",
                      "phone",
                      e.target.value
                    )
                  }
                  placeholder="输入联系电话"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">消防中心地址</label>
                <Input
                  value={safeContacts.fireDepartment.address}
                  onChange={(e) =>
                    updateContactField(
                      "fireDepartment",
                      "address",
                      e.target.value
                    )
                  }
                  placeholder="输入消防中心地址"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">导航路线</label>
                <Textarea
                  value={safeContacts.fireDepartment.directions}
                  onChange={(e) =>
                    updateContactField(
                      "fireDepartment",
                      "directions",
                      e.target.value
                    )
                  }
                  placeholder="输入从施工现场到消防中心的导航路线"
                  rows={2}
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
            </div>
          </div>
          <div className="space-y-3">
            <h4 className="font-medium text-gray-800 flex items-center gap-2">
              <Shield className="w-4 h-4 text-blue-600" />
              最近派出所
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 pl-6">
              <div>
                <label className="text-sm text-gray-600">派出所名称</label>
                <Input
                  value={safeContacts.policeStation.name}
                  onChange={(e) =>
                    updateContactField("policeStation", "name", e.target.value)
                  }
                  placeholder="输入派出所名称"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div>
                <label className="text-sm text-gray-600">联系电话</label>
                <Input
                  value={safeContacts.policeStation.phone}
                  onChange={(e) =>
                    updateContactField("policeStation", "phone", e.target.value)
                  }
                  placeholder="输入联系电话"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">派出所地址</label>
                <Input
                  value={safeContacts.policeStation.address}
                  onChange={(e) =>
                    updateContactField(
                      "policeStation",
                      "address",
                      e.target.value
                    )
                  }
                  placeholder="输入派出所地址"
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-sm text-gray-600">导航路线</label>
                <Textarea
                  value={safeContacts.policeStation.directions}
                  onChange={(e) =>
                    updateContactField(
                      "policeStation",
                      "directions",
                      e.target.value
                    )
                  }
                  placeholder="输入从施工现场到派出所的导航路线"
                  rows={2}
                  className="mt-1"
                  disabled={disabled}
                />
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default function EmergencyPlanManager({ scheme, onUpdate, disabled }) {
  const { toast } = useToast();
  const [isGenerating, setIsGenerating] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);

  // New state for AI analysis
  const [isAnalyzingWithAI, setIsAnalyzingWithAI] = useState(false);
  const [aiRecommendations, setAiRecommendations] = useState([]);
  const [showAIConfirmDialog, setShowAIConfirmDialog] = useState(false);

  const handleUpdateField = (field, value) => {
    onUpdate({ ...scheme, [field]: value });
  };

  const handleUpdateMeasures = (measures) => {
    onUpdate({ ...scheme, emergencyResponseMeasures: measures });
  };

  const handleAddMeasure = () => {
    const newMeasure = {
      id: `manual-${Date.now()}`,
      incident_type: "新事件",
      description: "",
      immediate_actions: "",
      requiredEquipment: "",
      responsible_person: "",
    };
    const updatedMeasures = [
      ...(scheme.emergencyResponseMeasures || []),
      newMeasure,
    ];
    handleUpdateMeasures(updatedMeasures);
  };

  const handleRemoveMeasure = (idToRemove) => {
    const updatedMeasures = (scheme.emergencyResponseMeasures || []).filter(
      (m) => m.id !== idToRemove
    );
    handleUpdateMeasures(updatedMeasures);
  };

  const handleManualImport = (importedTemplates) => {
    if (!Array.isArray(importedTemplates)) return;

    const existingMeasureIncidents = new Set(
      (scheme.emergencyResponseMeasures || []).map((m) => m.incident_type)
    );

    const newMeasures = importedTemplates
      .filter(
        (template) => !existingMeasureIncidents.has(template.incident_type)
      )
      .map((template) => ({
        id: `imported-${template.id}-${Date.now()}`,
        incident_type: template.incident_type,
        description: template.description,
        immediate_actions: Array.isArray(template.immediate_actions)
          ? template.immediate_actions.join("\n")
          : "",
        requiredEquipment: template.requiredEquipment,
        responsible_person: template.responsible_person_role,
      }));

    if (newMeasures.length > 0) {
      const updatedMeasures = [
        ...(scheme.emergencyResponseMeasures || []),
        ...newMeasures,
      ];
      handleUpdateMeasures(updatedMeasures);
      toast({
        title: "✅ 导入成功",
        description: `已成功导入 ${newMeasures.length} 条应急措施。`,
      });
    } else {
      toast({
        title: "ℹ️ 无新措施",
        description: "所有选中的措施均已存在于方案中。",
      });
    }
  };

  // c
  const handleAIAnalysis = async () => {
    if (!scheme || !scheme.id) {
      toast({
        variant: "destructive",
        title: "❌ 分析失败",
        description: "方案数据不完整，无法进行AI分析。",
      });
      return;
    }

    setIsAnalyzingWithAI(true);
    toast({
      title: "🤖 AI分析启动",
      description: "正在分析施工步骤风险，并从知识库匹配应急措施...",
    });

    try {
      // 1. Fetch all necessary data
      const [SafetyRiskPointData, EmergencyMeasureTemplateData] =
        await Promise.all([
          SafetyRiskPointAPI.getList(),
          EmergencyMeasureTemplateAPI.getList(),
        ]);
      const allRisks = SafetyRiskPointData.data
      const allEmergencyTemplates = EmergencyMeasureTemplateData.data;
      const { constructionSteps } = scheme;
      if (!constructionSteps || constructionSteps.length === 0) {
        toast({
          title: "ℹ️ 无施工步骤",
          description: "当前方案没有施工步骤，无法进行风险分析。",
        });
        setIsAnalyzingWithAI(false);
        return;
      }

      // 2. Prepare data for the AI prompt
      const riskMap = new Map(allRisks.map((r) => [r.riskCode, r]));
      const identifiedRisks = new Set();

      constructionSteps.forEach((step) => {
        (step.associatedRiskCodes || []).forEach((code) => {
          if (riskMap.has(code)) {
            identifiedRisks.add(riskMap.get(code));
          }
        });
      });

      if (identifiedRisks.size === 0) {
        toast({
          title: "ℹ️ 无关联风险",
          description: "施工步骤中未识别到风险点，无法推荐应急措施。",
        });
        setIsAnalyzingWithAI(false);
        return;
      }

      const identifiedRisksText = Array.from(identifiedRisks)
        .map(
          (r) =>
            `- ${r.risk_name} (${r.riskCode}): ${
              r.risk_description
            }. Primary Category: ${
              r.primary_category
            }, Risk Types: ${r.risk_type.join(", ")}.`
        )
        .join("\n");

      const availableMeasuresText = allEmergencyTemplates
        .map(
          (t) =>
            `- ID: ${t.id}, Category: ${t.category}, Incident: ${t.incident_type}, Description: ${t.description}`
        )
        .join("\n");

      // 3. Construct the AI prompt
      const prompt = `
        You are an expert safety supervisor for a major power grid company. Your task is to analyze the safety risks of a construction scheme and propose the most relevant emergency response measures.

        **Construction Scheme Context:**
        The scheme involves several construction steps which have identified the following key safety risks:
        ${identifiedRisksText}

        **Available Emergency Measure Templates:**
        Here is a list of standard emergency measure templates from our knowledge base:
        ${availableMeasuresText}

        **Your Task:**
        Based on the identified risks, select the most appropriate emergency measure templates from the provided list. Consider the risk types (e.g., 'electrical', 'fall from height') and their potential consequences.

        Return a JSON object with a single key "recommended_ids", which is an array of the string IDs of the templates you recommend. Do not include templates that are not relevant.
      `;

      // 4. Call the LLM directly
      const llmResponse = await InvokeLLM({
        prompt: prompt,
        responseJsonSchema: {
          type: "object",
          properties: {
            recommended_ids: {
              type: "array",
              items: { type: "string" },
              description:
                "An array of IDs of the recommended emergency measure templates.",
            },
          },
          required: ["recommended_ids"],
        },
      });

      console.log(
        `[AI Analysis] LLM recommended IDs:`,
        llmResponse.recommended_ids
      );

      const recommendedIds = llmResponse.recommended_ids || [];

      if (recommendedIds.length === 0) {
        toast({
          title: "✅ 分析完成",
          description: "根据当前风险分析，AI未推荐新的应急措施。",
        });
        setIsAnalyzingWithAI(false);
        return;
      }

      const recommendedTemplates = allEmergencyTemplates.filter((t) =>
        recommendedIds.includes(t.id)
      );

      setAiRecommendations(recommendedTemplates);
      setShowAIConfirmDialog(true);
    } catch (error) {
      console.error("AI analysis for emergency measures failed:", error);
      toast({
        variant: "destructive",
        title: "❌ AI分析失败",
        description: error.message || "无法获取AI建议，请稍后重试。",
      });
    } finally {
      setIsAnalyzingWithAI(false);
    }
  };

  // Function to confirm and import AI recommendations
  const handleConfirmAIImport = () => {
    const existingMeasureIncidents = new Set(
      (scheme.emergencyResponseMeasures || []).map((m) => m.incident_type)
    );

    const newMeasures = aiRecommendations
      .filter(
        (template) => !existingMeasureIncidents.has(template.incident_type)
      )
      .map((template) => ({
        id: `imported-${template.id}-${Date.now()}`,
        incident_type: template.incident_type,
        description: template.description || "",
        immediate_actions: Array.isArray(template.immediate_actions)
          ? template.immediate_actions.join("\n")
          : template.immediate_actions || "",
        requiredEquipment: template.requiredEquipment || "",
        responsible_person: template.responsible_person_role || "",
      }));

    if (newMeasures.length > 0) {
      const updatedMeasures = [
        ...(scheme.emergencyResponseMeasures || []),
        ...newMeasures,
      ];
      handleUpdateMeasures(updatedMeasures);
      toast({
        title: "✅ 导入成功",
        description: `已成功导入 ${newMeasures.length} 条AI推荐的应急措施。`,
      });
    } else {
      toast({
        title: "ℹ️ 无新措施",
        description: "AI推荐的所有措施均已存在于方案中。",
      });
    }

    setShowAIConfirmDialog(false);
    setAiRecommendations([]);
  };

  return (
    <div className="space-y-6">
      <EmergencyContactEditor
        contacts={scheme?.emergencyContacts || {}}
        onUpdate={onUpdate}
        disabled={disabled}
      />

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Shield className="w-5 h-5 text-red-600" />
              常见事故事件现场处置措施
            </CardTitle>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={handleAIAnalysis}
                disabled={disabled || isAnalyzingWithAI}
                className="bg-orange-500 hover:bg-orange-600 text-white border-orange-600"
              >
                {isAnalyzingWithAI ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    AI分析中...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4 mr-2" />
                    AI智能分析并导入
                  </>
                )}
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowImportModal(true)}
                disabled={disabled}
              >
                <BookOpen className="w-4 h-4 mr-2" />
                从知识库导入
              </Button>
              <Button size="sm" onClick={handleAddMeasure} disabled={disabled}>
                <Plus className="w-4 h-4 mr-2" />
                手动添加
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {(scheme.emergencyResponseMeasures || []).map((measure, index) => (
            <div
              key={measure.id}
              className="p-4 border rounded-lg bg-gray-50/50"
            >
              <div className="flex justify-between items-start mb-2">
                <Input
                  value={measure.incident_type || ""}
                  onChange={(e) => {
                    const newMeasures = [...scheme.emergencyResponseMeasures];
                    newMeasures[index].incident_type = e.target.value;
                    handleUpdateMeasures(newMeasures);
                  }}
                  className="text-md font-semibold border-0 shadow-none p-0 focus-visible:ring-0"
                  disabled={disabled}
                  placeholder="事件类型"
                />
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleRemoveMeasure(measure.id)}
                  disabled={disabled}
                >
                  <Trash2 className="w-4 h-4 text-red-500" />
                </Button>
              </div>
              <div className="space-y-3">
                <div>
                  <Label>事件描述</Label>
                  <Textarea
                    value={measure.description || ""}
                    onChange={(e) => {
                      const newMeasures = [...scheme.emergencyResponseMeasures];
                      newMeasures[index].description = e.target.value;
                      handleUpdateMeasures(newMeasures);
                    }}
                    rows={2}
                    disabled={disabled}
                    placeholder="详细描述此事件的性质和可能影响"
                  />
                </div>
                <div>
                  <Label>立即处置措施</Label>
                  <Textarea
                    value={measure.immediate_actions || ""}
                    onChange={(e) => {
                      const newMeasures = [...scheme.emergencyResponseMeasures];
                      newMeasures[index].immediateActions = e.target.value;
                      handleUpdateMeasures(newMeasures);
                    }}
                    rows={4}
                    placeholder="分点说明处理步骤，例如：1. 立即疏散人员；2. 切断电源..."
                    disabled={disabled}
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>所需应急设备/工具</Label>
                    <Input
                      value={measure.requiredEquipment || ""}
                      onChange={(e) => {1
                        const newMeasures = [
                          ...scheme.emergencyResponseMeasures,
                        ];
                        newMeasures[index].requiredEquipment = e.target.value;
                        handleUpdateMeasures(newMeasures);
                      }}
                      disabled={disabled}
                      placeholder="例如：灭火器、急救箱、警戒线"
                    />
                  </div>
                  <div>
                    <Label>主要负责人</Label>
                    <Input
                      value={measure.responsible_person || ""}
                      onChange={(e) => {
                        const newMeasures = [
                          ...scheme.emergencyResponseMeasures,
                        ];
                        newMeasures[index].responsible_person = e.target.value;
                        handleUpdateMeasures(newMeasures);
                      }}
                      placeholder="例如：现场负责人、安全员"
                      disabled={disabled}
                    />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-purple-600" />
            应急信息报送流程
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Textarea
            value={scheme.emergencyReportingProcess || ""}
            onChange={(e) =>
              handleUpdateField("emergencyReportingProcess", e.target.value)
            }
            rows={5}
            placeholder="描述发现事故后的信息上报流程、联系人及联系方式..."
            disabled={disabled}
          />
        </CardContent>
      </Card>

      {/* Manual Import Modal */}
      <EmergencyMeasureImportModal
        open={showImportModal}
        onOpenChange={setShowImportModal}
        onImport={handleManualImport}
      />

      {/* AI Confirmation Dialog */}
      <Dialog open={showAIConfirmDialog} onOpenChange={setShowAIConfirmDialog}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Sparkles className="w-5 h-5 text-orange-500" />
              AI应急措施推荐
            </DialogTitle>
            <DialogDescription>
              根据您在施工步骤中识别的风险，AI推荐以下应急措施。已存在的措施不会重复导入。
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            {aiRecommendations.length === 0 ? (
              <p className="text-center text-gray-500">
                AI没有找到合适的推荐。
              </p>
            ) : (
              <ScrollArea className="h-[300px] border rounded-md p-4 space-y-3">
                {aiRecommendations.map((template) => (
                  <div key={template.id} className="p-3 bg-gray-50 rounded-lg">
                    <p className="font-semibold text-gray-800">
                      {template.incident_type}
                    </p>
                    <p className="text-sm text-gray-600 line-clamp-2">
                      {template.description}
                    </p>
                  </div>
                ))}
              </ScrollArea>
            )}
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowAIConfirmDialog(false)}
            >
              取消
            </Button>
            <Button
              onClick={handleConfirmAIImport}
              disabled={aiRecommendations.length === 0}
            >
              <Check className="w-4 h-4 mr-2" />
              确认导入 ({aiRecommendations.length})
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
